package com.springboot.hiresystem.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.springboot.hiresystem.domain.Favorites;
import com.springboot.hiresystem.dto.req.FavoritesQueryRequestDTO;
import com.springboot.hiresystem.dto.req.FavoritesUpdateRequestDTO;
import com.springboot.hiresystem.dto.resp.FavoritesResponseDTO;
import com.springboot.hiresystem.dto.resp.PageResponse;
import com.springboot.hiresystem.dto.resp.Result;
import com.springboot.hiresystem.service.FavoritesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

@RestController
@RequestMapping("/favorites")
@Slf4j
public class FavoritesController {

    private final FavoritesService favoritesService;

    public FavoritesController(FavoritesService favoritesService) {
        this.favoritesService = favoritesService;
    }

    // 带分页和条件查询
    @GetMapping("/list")
    public Result<PageResponse<FavoritesResponseDTO>> list(FavoritesQueryRequestDTO request) {
        QueryWrapper<Favorites> queryWrapper = new QueryWrapper<>();
        if (request.getUserId() != null) {
            queryWrapper.eq("user_id", request.getUserId());
        }
        if (request.getJobId() != null) {
            queryWrapper.eq("job_id", request.getJobId());
        }
        queryWrapper.orderByAsc("user_id");

        Page<Favorites> page = new Page<>(request.getPage(), request.getSize());
        Page<Favorites> resultPage = favoritesService.page(page, queryWrapper);

        List<FavoritesResponseDTO> dtoList = BeanUtil.copyToList(resultPage.getRecords(), FavoritesResponseDTO.class);

        PageResponse<FavoritesResponseDTO> response = new PageResponse<>();
        response.setTotal(resultPage.getTotal());
        response.setList(dtoList);

        return Result.success(response);
    }

    // 条件查询
    @PostMapping("/query")
    public Result<List<FavoritesResponseDTO>> query(@RequestBody FavoritesQueryRequestDTO request) {
        QueryWrapper<Favorites> queryWrapper = new QueryWrapper<>();

        if (request.getUserId() != null) {
            queryWrapper.eq("user_id", request.getUserId());
        }
        if (request.getJobId() != null) {
            queryWrapper.eq("job_id", request.getJobId());
        }

        List<Favorites> favorites = favoritesService.list(queryWrapper);
        List<FavoritesResponseDTO> dtoList = BeanUtil.copyToList(favorites, FavoritesResponseDTO.class);

        return Result.success(dtoList);
    }

    // 更新或添加
    @PostMapping("/update")
    public Result<String> update(@RequestBody FavoritesUpdateRequestDTO request) {
        Favorites favorite = BeanUtil.copyProperties(request, Favorites.class);
        if (favorite.getUserId() != null && favorite.getJobId() != null) {
            // 检查是否已存在相同的收藏记录
            QueryWrapper<Favorites> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", favorite.getUserId());
            queryWrapper.eq("job_id", favorite.getJobId());
            List<Favorites> existingFavorites = favoritesService.list(queryWrapper);

            if (!existingFavorites.isEmpty()) {
                return Result.failure(500, "该收藏记录已存在");
            }
            if  (favorite.getFavoritedAt() == null) {
//                return Result.failure(500, "收藏时间不能为空");
            }else {
            // 将 favoritedAt 字符串转换为 Date 类型
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                favorite.setFavoritedAt(sdf.parse(request.getFavoritedAt()));
            } catch (ParseException e) {
                return Result.failure(500, "日期格式错误，请使用 yyyy-MM-dd HH:mm:ss 格式");
            }
            }
            if (!favoritesService.save(favorite)) {
                return Result.failure(500, "添加失败");
            }
            return Result.success("新增成功");
        } else {
            return Result.failure(500, "用户ID和职位ID不能为空");
        }
    }

    // 删除
    @PostMapping("/delete")
    public Result<String> delete(@RequestBody Favorites favorite) {
        QueryWrapper<Favorites> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", favorite.getUserId());
        queryWrapper.eq("job_id", favorite.getJobId());

        boolean isDeleted = favoritesService.remove(queryWrapper);
        if (isDeleted) {
            return Result.success("删除成功");
        } else {
            return Result.failure(500, "删除失败");
        }
    }
}